package com.erp.web.controller.framework;

import com.erp.framework.annotation.Log;
import com.erp.framework.constant.Constants;
import com.erp.framework.core.controller.BaseController;
import com.erp.framework.core.domain.AjaxResult;
import com.erp.framework.core.page.TableDataInfo;
import com.erp.framework.domain.SysRole;
import com.erp.framework.domain.SysUser;
import com.erp.framework.domain.SysUserRole;
import com.erp.framework.enums.BusinessType;
import com.erp.framework.service.ISysRoleService;
import com.erp.framework.service.ISysUserService;
import com.erp.framework.util.ShiroUtils;
import com.erp.framework.util.poi.ExcelUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色信息
 *
 * @author erp
 */
@Controller
@RequestMapping("/framework/role")
public class SysRoleController extends BaseController {

    private final String prefix = "framework/role";

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysUserService userService;

    @RequiresPermissions("framework:role:view")
    @GetMapping()
    public String role() {
        return prefix + "/role";
    }

    @RequiresPermissions("framework:role:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysRole role) {
        startPage();
        List<SysRole> list = roleService.list(role);
        return getDataTable(list);
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("framework:role:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysRole role) {
        List<SysRole> list = roleService.list(role);
        ExcelUtil<SysRole> util = new ExcelUtil<>(SysRole.class);
        return util.exportExcel(list, "角色数据");
    }

    /**
     * 新增角色
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存角色
     */
    @RequiresPermissions("framework:role:add")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysRole role) {
        if (roleService.checkRoleNameUnique(role)) {
            return error("新增角色'" + role.getName() + "'失败，角色名称已存在");
        }
        if (roleService.checkCodeUnique(role)) {
            return error("新增角色'" + role.getName() + "'失败，角色编码已存在");
        }
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(roleService.insert(role));

    }

    /**
     * 修改角色
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("role", roleService.selectRoleById(id));
        return prefix + "/edit";
    }

    /**
     * 修改保存角色
     */
    @RequiresPermissions("framework:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysRole role) {
        if (roleService.checkRoleNameUnique(role)) {
            return error("修改角色'" + role.getName() + "'失败，角色名称已存在");
        }
        if (roleService.checkCodeUnique(role)) {
            return error("修改角色'" + role.getName() + "'失败，角色编码已存在");
        }
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(roleService.update(role));
    }


    @RequiresPermissions("framework:role:remove")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(roleService.deleteRoleByIds(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 校验角色名称
     */
    @PostMapping("/checkRoleNameUnique")
    @ResponseBody
    public boolean checkRoleNameUnique(SysRole role) {
        return roleService.checkRoleNameUnique(role);
    }

    /**
     * 校验角色权限
     */
    @PostMapping("/checkCodeUnique")
    @ResponseBody
    public boolean checkCodeUnique(SysRole role) {
        return roleService.checkCodeUnique(role);
    }

    /**
     * 选择菜单树
     */
    @GetMapping("/selectMenuTree")
    public String selectMenuTree() {
        return prefix + "/tree";
    }

    /**
     * 分配用户
     */
    @RequiresPermissions("framework:role:edit")
    @GetMapping("/authUser/{id}")
    public String authUser(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("role", roleService.selectRoleById(id));
        return prefix + "/authUser";
    }

    /**
     * 查询已分配用户角色列表
     */
    @RequiresPermissions("framework:role:list")
    @PostMapping("/authUser/allocatedList")
    @ResponseBody
    public TableDataInfo allocatedList(SysUser user) {
        startPage();
        // user 的 id 值 实际是 勾选的 role 的 id
        user.getParams().put("roleId", user.getId());
        user.setId(null);
        List<SysUser> list = userService.list(user);
        return getDataTable(list);
    }

    /**
     * 取消授权
     */
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PostMapping("/authUser/cancel")
    @ResponseBody
    public AjaxResult cancelAuthUser(SysUserRole userRole) {
        return toAjax(roleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权
     */
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PostMapping("/authUser/cancelAll")
    @ResponseBody
    public AjaxResult cancelAuthUserAll(String roleId, String userIds) {
        return toAjax(roleService.deleteAuthUsers(roleId, userIds));
    }

    /**
     * 选择用户
     */
    @GetMapping("/authUser/selectUser/{id}")
    public String selectUser(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("role", roleService.selectRoleById(id));
        return prefix + "/selectUser";
    }

    /**
     * 查询未分配用户角色列表
     */
    @RequiresPermissions("framework:role:list")
    @PostMapping("/authUser/unallocatedList")
    @ResponseBody
    public TableDataInfo unallocatedList(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUnallocatedList(user);
        return getDataTable(list);
    }

    /**
     * 批量选择用户授权
     */
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PostMapping("/authUser/selectAll")
    @ResponseBody
    public AjaxResult selectAuthUserAll(String roleId, String userIds) {
        return toAjax(roleService.insertAuthUsers(roleId, userIds));
    }
}